const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const log = require("electron-log");
const { autoUpdater } = require("electron-updater");
const path = require("path");
const url = require("url");
require("@electron/remote/main").initialize(); // needed to upgrade

log.transports.file.file = require("os").homedir() + "/AoW-Launcher-log.txt";
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
log.info("App starting...");

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 840,
    minWidth: 614,
    height: 480,
    minHeight: 360,
    webPreferences: {
      webviewTag: true, // needed to upgrade
      nodeIntegration: true, // needed to upgrade
      contextIsolation: false, // needed to upgrade
      enableRemoteModule: true, // needed to upgrade
    },
    titleBarStyle: "hidden",
    // show: false,
    // autoHideMenuBar: true,
    icon: path.join(__dirname, "/img/logo.png"),
    frame: false,
  });
  require("@electron/remote/main").enable(mainWindow.webContents); // needed to upgrade
  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, "index.html"),
      protocol: "file:",
      slashes: true,
    })
  );

  if (require("electron-is-dev")) mainWindow.webContents.openDevTools();
  mainWindow.once("ready-to-show", () => {
    mainWindow.show();
    // mainWindow.webContents.openDevTools();
  });
  mainWindow.once("closed", () => (mainWindow = null));

  mainWindow.on("new-window-for-tab", (event) => {
    console.log("new tab event", event);
  });

  mainWindow.webContents.on("new-window", function (event, url) {
    console.log("new window event", event, url);
    event.preventDefault();
    shell.openExternal(url);
  });
}

app.on("ready", createWindow);
app.on("window-all-closed", () => app.exit());
app.on("before-quit", () => app.exit());

ipcMain.on("open-directory-dialog", function (event, response) {
  dialog
    .showOpenDialog({
      properties: ["openDirectory"],
    })
    .then((files) => {
      if (files && files.filePaths.length)
        event.sender.send(response, files.filePaths[0]);
    });
});

autoUpdater.on("update-downloaded", (info) => {
  autoUpdater.quitAndInstall();
});

autoUpdater.on("download-progress", (progress) => {
  mainWindow.webContents.send("download-progress", progress);
});

autoUpdater.on("update-available", (info) => {
  mainWindow.webContents.send(
    "downloading-update",
    "Downloading version " + info.version
  );
});

app.on("ready", function () {
  autoUpdater.checkForUpdates();
});
